package com.guyu.common.web.filter;

import cn.hutool.core.util.IdUtil;
import com.guyu.common.core.constant.Constants;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.IOException;


@Slf4j
public class RequestIdFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        try {
            //生成requestId
            String requestId = getRequestId();
            MDC.put(Constants.REQUEST_ID, requestId);
            //设置到响应头
            if (response instanceof HttpServletResponse httpServletResponse) {
                httpServletResponse.addHeader(Constants.X_REQUEST_ID, requestId);
            }
            chain.doFilter(request, response);
        } finally {
            // 避免线程复用，互相干扰
            MDC.remove(Constants.REQUEST_ID);
        }
    }


    private String getRequestId() {
        return "req_" + IdUtil.fastSimpleUUID();
    }

}
